﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace iPhotoUploader.Library
{
    public static class ImageUtility
    {
        public static Byte[] ResizeNew(string imagePath, string imageName, int target)
        {
            using (var image = Image.FromFile(imagePath))
            {
                int sourceX = 0;
                int sourceY = 0;
                float percentage;
                int sourceWidth = image.Width;
                int sourceHeight = image.Height;

                if (sourceWidth > sourceHeight)
                    percentage = (float) target/sourceWidth; // Landscape
                else
                    percentage = (float) target/sourceHeight; // Protrait

                int destX = 0;
                int destY = 0;
                int destWidth = (int) (sourceWidth*percentage);
                int destHeight = (int) (sourceHeight*percentage);

                using (var bitmap = new Bitmap(destWidth, destHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
                {
                    //bitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);
                    using (var graphics = Graphics.FromImage(bitmap))
                    {
                        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        graphics.DrawImage(image,
                                        new Rectangle(destX, destY, destWidth, destHeight),
                                        new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                                        GraphicsUnit.Pixel);
                    }
                    var stream = new MemoryStream();

                    bitmap.Save(stream, ImageFormat.Jpeg);

                    return stream.ToArray();
                }
            }
        }
    }
}
